package com.example.reward.fragments;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.reward.R;
import com.example.reward.api.ApiCallback;
import com.example.reward.api.ApiClient;
import com.example.reward.api.RewardApi;
import com.example.reward.response.Result;
import com.example.reward.response.UserDto;
import com.google.android.material.snackbar.Snackbar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ProfileFragment extends Fragment {

    private ImageView imageAvatar;
    private TextView textNickname, textEmail;
    private Button btnEdit;

    private Long id = 1L;
    private String nickname = "小明";
    private String email = "example@email.com";
    private final RewardApi rewardApi = ApiClient.getClient().create(RewardApi.class);

    private ActivityResultLauncher<String> pickImageLauncher;
    private ActivityResultLauncher<String> permissionLauncher;

    public ProfileFragment() {
        super(R.layout.fragment_profile);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 注册选择图片
        pickImageLauncher = registerForActivityResult(
                new ActivityResultContracts.GetContent(),
                uri -> {
                    if (uri != null) {
                        try {
                            File localFile = copyUriToInternalStorage(uri);
                            saveDbAvatar(localFile);
                            saveAvatarPath(localFile.getAbsolutePath());
                            Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                            imageAvatar.setImageBitmap(bitmap);                        } catch (IOException e) {
                            Toast.makeText(getContext(), "头像保存失败", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }
                }
        );

        // 注册权限申请
        permissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        pickImageLauncher.launch("image/*");
                    } else {
                        Toast.makeText(getContext(), "没有读取媒体的权限", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    public void saveDbAvatar(File file) {
        // 创建 RequestBody，用于封装文件数据和MIME类型
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);

        // MultipartBody.Part 结合文件名一起发送
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        // 普通参数 userId，构造 RequestBody
        RequestBody userId = RequestBody.create(MediaType.parse("text/plain"), id.toString());

        rewardApi.updateAvatar(body, userId).enqueue(new ApiCallback<>() {
            @Override
            public void onSuccess(Result<Integer> result) {
                Toast.makeText(getContext(), "数据库头像数据更新成功！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(getContext(), "数据库头像数据更新失败！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private File copyUriToInternalStorage(Uri uri) throws IOException {
        File file = new File(requireContext().getFilesDir(), "avatar.jpg");
        try (InputStream in = requireContext().getContentResolver().openInputStream(uri);
             OutputStream out = new FileOutputStream(file)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
        return file;
    }

    private void saveAvatarPath(String path) {
        requireContext()
                .getSharedPreferences("profile", Context.MODE_PRIVATE)
                .edit()
                .putString("avatar_path", path)
                .apply();
    }

    private String loadAvatarPath() {
        return requireContext()
                .getSharedPreferences("profile", Context.MODE_PRIVATE)
                .getString("avatar_path", null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        imageAvatar = view.findViewById(R.id.image_avatar);
        textNickname = view.findViewById(R.id.text_nickname);
        textEmail = view.findViewById(R.id.text_email);
        btnEdit = view.findViewById(R.id.btn_edit);

        loadProfile(view);

        // 加载本地头像
        String localAvatarPath = loadAvatarPath();
        if (localAvatarPath != null) {
            File avatarFile = new File(localAvatarPath);
            if (avatarFile.exists()) {
                imageAvatar.setImageURI(Uri.fromFile(avatarFile));
            }
        }

        // 点击头像选择新图片
        imageAvatar.setOnClickListener(v -> checkPermissionAndSelectImage());

        btnEdit.setOnClickListener(v -> showEditDialog());
    }

    private void checkPermissionAndSelectImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用 READ_MEDIA_IMAGES
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_IMAGES)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionLauncher.launch(Manifest.permission.READ_MEDIA_IMAGES);
            } else {
                pickImageLauncher.launch("image/*");
            }
        } else {
            // Android 12 及以下
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
            } else {
                pickImageLauncher.launch("image/*");
            }
        }
    }

    public void loadProfile(View view) {
        rewardApi.getProfile().enqueue(new ApiCallback<>() {
            @Override
            public void onSuccess(UserDto result) {
                id = result.getId();
                email = result.getMail();
                nickname = result.getNickName();
                updateUI();
            }

            @Override
            public void onError(String errorMsg) {
                Snackbar.make(view, "加载个人信息数据失败：" + errorMsg, Snackbar.LENGTH_LONG).show();
            }
        });
    }

    private void updateUI() {
        textNickname.setText("昵称：" + nickname);
        textEmail.setText("邮箱：" + email);
    }

    private void showEditDialog() {
        View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_edit_profile, null);
        EditText editNickname = dialogView.findViewById(R.id.edit_nickname);
        EditText editEmail = dialogView.findViewById(R.id.edit_email);

        editNickname.setText(nickname);
        editEmail.setText(email);

        new AlertDialog.Builder(getContext())
                .setTitle("编辑资料")
                .setView(dialogView)
                .setPositiveButton("保存", (dialog, which) -> {
                    String newNickname = editNickname.getText().toString().trim();
                    String newEmail = editEmail.getText().toString().trim();

                    if (newNickname.isEmpty()) {
                        Toast.makeText(getContext(), "昵称不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!isValidEmail(newEmail)) {
                        Toast.makeText(getContext(), "邮箱格式不正确", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    nickname = newNickname;
                    email = newEmail;
                    updateUI();

                    UserDto userDto = new UserDto();
                    userDto.setId(id);
                    userDto.setNickName(nickname);
                    userDto.setMail(email);

                    rewardApi.updateProfile(userDto).enqueue(new ApiCallback<>() {
                        @Override
                        public void onSuccess(UserDto result) {
                            Toast.makeText(getContext(), "资料已更新", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onError(String errorMsg) {
                            Toast.makeText(getContext(), "资料更新失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private boolean isValidEmail(String email) {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }
}
